package com.example.order.service;

import com.example.order.jpa.OrderRepository;
import com.example.order.pojo.Order;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class OrderService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private OrderRepository orderRepository;

    //下单
    public String save(Long userId, BigDecimal amount){
        Order order = new Order();
        order.setAmount(amount);
        order.setCreateTime(new Date());
        order.setOrderNo(UUID.randomUUID().toString());
        order.setStatus(Order.STATUS_UNPAID);
        order.setUpdateTime(order.getCreateTime());
        order.setUserId(userId);
        orderRepository.save(order);
        //发送至MQ
        Message message = MessageBuilder.withBody(order.getOrderNo().getBytes()).build();
        amqpTemplate.send("exchange.order", "rk.order", message);

        return order.getOrderNo();
    }

    //支付
    public Boolean pay(String orderNo){
        Order order = orderRepository.findByOrderNo(orderNo);
        if(order == null){
            throw new IllegalArgumentException("orderNo : 不存在->" + orderNo);
        }
        if(order.getStatus().equals(Order.STATUS_PAID)){
            throw new RuntimeException("订单已经支付: " + orderNo);
        }
        if(order.getStatus().equals(Order.STATUS_UNPAID)){
            order.setStatus(Order.STATUS_PAID);
            order.setUpdateTime(new Date());
            orderRepository.save(order);
            return true;
        }
        if(order.getStatus().equals(Order.STATUS_EXPIRED)){
            return false;
        }

        throw new RuntimeException("意外的订单状态: " + orderNo + "   " + order.getStatus());
    }

    //过期列表
    public List<Order> findByUserIdAndStatus(Long userId, Integer status){
        return orderRepository.findByUserIdAndStatus(userId,status);
    }


}
